package kr.ac.mju.mdc.mjuapp.green;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import kr.ac.mju.mdc.mjuapp.R;
import kr.ac.mju.mdc.mjuapp.http.HttpManager;
import kr.ac.mju.mdc.mjuapp.network.NetworkManager;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.Dialog;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author davidkim
 *
 */
public class GreencampusListActivity extends Activity implements OnItemClickListener {
	private final int PROGRESS_DIALOG = 10;
	private final int LOADING_SUCCESS = 11;
	private final int LOADING_FAIL = 12;
	private final int RQ_WRITE_BOARD = 20;

	private String listUrl;

	private GreencampusAdapter greencampusAdapter;
	private ArrayList<Greencampus> greencampusList;
	private ArrayList<String> pageUrlList;

	private int prevLastPositionOfList = 0;
	/**********************************************************
	 * handler
	 **********************************************************/
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			int what = msg.what;
			switch (what) {
			case LOADING_SUCCESS:
				// parsing
				HashMap<String, List<Element>> elementMap = (HashMap<String, List<Element>>) msg.obj;
				List<Element> tbodyElementsList = elementMap.get(HTMLElementName.TBODY);
				List<Element> pageElementsList = elementMap.get(HTMLElementName.DIV);
				// parsing page data
				if (pageElementsList != null && pageUrlList.size() == 0)
					parsingPageList(pageElementsList);
				if (pageUrlList.size() > 0) {
					// parsing list data
					if (tbodyElementsList != null)
						parsingList(tbodyElementsList);
				} else if (pageUrlList.size() == 0) {
					if (tbodyElementsList.size() > 0)
						parsingList(tbodyElementsList);
				}
				// dismissdialog
				dismissDialog(PROGRESS_DIALOG);
				// move listView on new top
				((ListView) findViewById(R.id.green_list_listview)).setSelection(prevLastPositionOfList);
				prevLastPositionOfList = greencampusList.size();
				break;
			case LOADING_FAIL:
				// dismissdialog
				dismissDialog(PROGRESS_DIALOG);
				// error weak signal msg
				Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_network_error_weak_signal),
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	/**********************************************************
	 * this is the first line of activity overrid methods
	 **********************************************************/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.greencampus_list_layout);

		// set url // greencampus board home url
		listUrl = new String("http://www.mju.ac.kr/mbs/mjukr/jsp/complaint2/list.jsp?boardId=7088978&id=mjukr_110500000000");
		// set pageUrlList
		pageUrlList = new ArrayList<String>();

		// set listview
		greencampusList = new ArrayList<Greencampus>();
		greencampusAdapter = new GreencampusAdapter(getApplicationContext(), greencampusList);
		ListView greenListView = (ListView) findViewById(R.id.green_list_listview);
		greenListView.setAdapter(greencampusAdapter);
		greenListView.setOnItemClickListener(this);
		greencampusAdapter.notifyDataSetChanged();

		// show list
		if (NetworkManager.checkNetwork(this))
			showListFromPost();

		// set write btn listener
		((ImageButton) findViewById(R.id.green_list_write_btn)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 글쓰기 버튼 누르면 첫 액티비티로 이동.
				Intent intent = new Intent(GreencampusListActivity.this, GreencampusMainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
		// set search btn listener
		((ImageButton) findViewById(R.id.green_list_search_btn)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (NetworkManager.checkNetwork(GreencampusListActivity.this))
					onSearchRequested();
			}
		});
		// set load next page listener
		((TextView) findViewById(R.id.green_list_more)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (NetworkManager.checkNetwork(GreencampusListActivity.this)) {
					if (pageUrlList.size() > 0) {
						listUrl = pageUrlList.get(0);
						pageUrlList.remove(0);
						showListFromPost();
					} else
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_load_more_last), Toast.LENGTH_SHORT)
								.show();
				}
			}
		});
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case PROGRESS_DIALOG:
			Dialog progressDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			progressDialog.setContentView(R.layout.loading_progress);
			progressDialog.setCancelable(false);
			return progressDialog;
		default:
			return null;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK) {
			if (requestCode == RQ_WRITE_BOARD) {
				// set board home url
				listUrl = new String("http://www.mju.ac.kr/mbs/mjukr/jsp/complaint2/list.jsp?boardId=7088978&id=mjukr_110500000000");
				// initList
				initList();
				// show list
				showListFromPost();
			}
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		setIntent(intent);
		if (intent.getAction().equals(Intent.ACTION_SEARCH)) {
			String keyword = intent.getStringExtra(SearchManager.QUERY);
			searchKeyword(keyword.trim());
		}
	}

	/**
	 * 
	 */
	private void showListFromPost() {
		showDialog(PROGRESS_DIALOG);
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// create httpManager
				HttpManager httpManager = new HttpManager();
				// init
				httpManager.init();
				// set httpPost
				httpManager.setHttpPost(listUrl);
				// httpResponse
				HttpResponse response = null;
				// execute
				try {
					response = httpManager.executeHttpPost();
					// get Status
					StatusLine status = response.getStatusLine();
					if (status.getStatusCode() == HttpStatus.SC_OK) {
						// html response result
						HttpEntity entity = response.getEntity();
						// parsing element
						Vector<String> tagNames = new Vector<String>();
						tagNames.add(HTMLElementName.TBODY);
						tagNames.add(HTMLElementName.DIV);
						// parse result
						HashMap<String, List<Element>> elementMap = httpManager.getHttpElementsMap(entity, tagNames);
						// send result to handler
						Message msg = handler.obtainMessage();
						msg.what = LOADING_SUCCESS;
						msg.obj = elementMap;
						handler.sendMessage(msg);
					} else
						handler.sendEmptyMessage(LOADING_FAIL);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(LOADING_FAIL);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(LOADING_FAIL);
					e.printStackTrace();
				} finally {
					httpManager.shutdown();
				}
			}
		});
		thread.start();
	}

	/**
	 * @param elementList
	 */
	private void parsingList(List<Element> elementList) {
		// get <tr> tags
		List<Element> trList = elementList.get(0).getAllElements(HTMLElementName.TR);

		for (Element trElement : trList) {
			// <tr> 1개의 6개의 <td>
			List<Element> tdList = trElement.getAllElements(HTMLElementName.TD);
			Greencampus greencampus = new Greencampus();
			boolean itHasNumber = true;
			// 세부 글 목록 정보 파싱.
			for (int index = 0; index < tdList.size(); index++) {
				// 글 번호 / 실제로 그린 캠퍼스 게시판 리스트에서는 글 번호를 출력하지 않으나
				// 검색 시에 검색결과에 등록 게시물이 없을 경우 처리를 위해 사용
				if (index == 0) {
					String num = tdList.get(index).getContent().toString().trim();
					/*
					 * 공지로 최상위 리스트에 올라와있는 경우, 실제 게시목록에도 중복 등록되어 있다. 이전 구현 버전에서는,
					 * 이것도 리스트에 포함시켰는데, '공지' 목록이 많을 경우, load more을 해도 계속 중복되서
					 * 리스트에 포함되는 경우가 발생한다. '공지'는 리스트에서 제외
					 */
					if (num.contains("<img")) {
						itHasNumber = false;
						break;
					}
					// 등록된 게시물이 없을 경우, return 처리
					else if (num.contains(getResources().getString(R.string.msg_no_list))) {
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_no_list), Toast.LENGTH_SHORT).show();
						return;
					}
				}
				// 글 번호가 있을 경우만 파싱
				if (itHasNumber) {
					// 제목
					if (index == 1) {
						Element aElement = tdList.get(index).getFirstElement(HTMLElementName.A);
						String subject = aElement.getContent().toString().trim();
						String url = aElement.getAttributeValue("href").trim();
						greencampus.setP_subject(subject);
						greencampus.setP_url(url);
					}
					// 날짜
					else if (index == 2) {
						String date = tdList.get(index).getContent().toString();
						if (date == null)
							date = "날짜정보없음";
						greencampus.setP_date(date.trim());
					}
					// 처리상태
					else if (index == 3) {
						String status = tdList.get(index).getContent().toString();
						if (status == null)
							status = "처리상태정보없음";
						if (status.contains("<"))
							status = status.replaceAll("<{1}.[^<>]*>{1}", "");
						greencampus.setP_status(status.trim());
					}
					// 작성자
					else if (index == 4) {
						String writer = tdList.get(index).getContent().toString();
						if (writer == null)
							writer = "작성자비공개";
						greencampus.setP_writer(writer.trim());
					}
				}
			}
			// 글 번호가 있을 경우만 추가
			if (itHasNumber)
				greencampusList.add(greencampus);
		}
		greencampusAdapter.notifyDataSetChanged();
	}

	/**
	 * @param elementList
	 */
	private void parsingPageList(List<Element> elementList) {
		// get <div> element
		List<Element> divList = elementList.get(0).getAllElements(HTMLElementName.DIV);

		for (Element divElement : divList) {
			// get <div class="paging"> element
			String attr = divElement.getAttributeValue("class");
			if (attr != null) {
				if (attr.trim().equals("paging")) {
					// get <strong> element to find current page
					Element strongElement = divElement.getFirstElement(HTMLElementName.STRONG);
					String currentPage = strongElement.getContent().toString().trim();
					if (currentPage != null) {
						// get <a> element list
						List<Element> aList = divElement.getAllElements(HTMLElementName.A);
						// get nextPages
						for (Element aElement : aList) {
							String content = aElement.getContent().toString().trim();
							// 처음 목록 이동, 이전 목록으로 이동은 제외시킨다
							// 다음 목록으로 이동과, 마지막 목록으로 이동만 포함한다
							// 다음 목록으로 이동이 있을 경우 , 마지막 목록으로 이동은 포함시키지 않는다
							if (content.startsWith("<img")) {
								String title = aElement.getAttributeValue("title").trim();
								if (title.startsWith("다음")) {
									String url = "http://www.mju.ac.kr/mbs/mjukr/jsp/complaint2/"
											+ aElement.getAttributeValue("href").trim();
									pageUrlList.add(url);
									break;
								}
							}
							// 페이지 넘버의 경우, 현재 페이지 보다 높은 페이지만 포함시킨다
							else if (Integer.valueOf(content) > Integer.valueOf(currentPage)) {
								String url = "http://www.mju.ac.kr/mbs/mjukr/jsp/complaint2/" + aElement.getAttributeValue("href").trim();
								pageUrlList.add(url);
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 
	 */
	private void initList() {
		// clear List
		greencampusList.clear();
		pageUrlList.clear();
		greencampusAdapter.notifyDataSetChanged();
		prevLastPositionOfList = 0;
	}

	/**
	 * 
	 */
	private void showListFromGet() {
		// showDialog
		showDialog(PROGRESS_DIALOG);
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// create httpManager
				HttpManager httpManager = new HttpManager();
				// init
				httpManager.init();
				// set httpPost
				httpManager.setHttpGet(listUrl);
				// httpResponse
				HttpResponse response = null;
				// execute
				try {
					response = httpManager.executeHttpGet();
					// get Status
					StatusLine status = response.getStatusLine();
					if (status.getStatusCode() == HttpStatus.SC_OK) {
						// html response result
						HttpEntity entity = response.getEntity();
						// parsing element
						Vector<String> tagNames = new Vector<String>();
						tagNames.add(HTMLElementName.TBODY);
						tagNames.add(HTMLElementName.DIV);
						// parse result
						HashMap<String, List<Element>> elementMap = httpManager.getHttpElementsMap(entity, tagNames);
						// send result to handler
						Message msg = handler.obtainMessage();
						msg.what = LOADING_SUCCESS;
						msg.obj = elementMap;
						handler.sendMessage(msg);
					} else
						handler.sendEmptyMessage(LOADING_FAIL);
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(LOADING_FAIL);
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					handler.sendEmptyMessage(LOADING_FAIL);
					e.printStackTrace();
				} finally {
					httpManager.shutdown();
				}
			}
		});
		thread.start();
	}

	/**
	 * @param keyword
	 */
	private void searchKeyword(String keyword) {
		// set searchUrl
		listUrl = "http://www.mju.ac.kr/mbs/mjukr/jsp/complaint2/list.jsp?boardId=7088978&listType=07&id=mjukr_110500000000&column=TITLE&search="
				+ keyword;
		// clear list
		initList();
		// showList
		showListFromGet();
		// setMainTitle
		((TextView) findViewById(R.id.green_list_main_title)).setText("");
		((TextView) findViewById(R.id.green_list_main_title)).setText(getResources().getString(R.string.title_search));
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(GreencampusListActivity.this, GreencampusViewActivity.class);
		intent.putExtra("url", greencampusList.get(position).getP_url());
		startActivity(intent);
	}
}

/* end of file */
